<template>
  <div>
    <div class="content">
      <div class="search">
        <template>
          <el-select
            v-model="searchValue"
            filterable
            clearable
            remote
            @blur="searchBlur"
            @change="searchTextChange"
            reserve-keyword
            @clear="clear"
            placeholder="请输入姓名,如果不更新,点击右侧搜索按钮"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in searchList"
              :key="item.sId"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </template>
        <!-- 搜索按钮 -->
        <el-button
          type="primary"
          plain
          class="search-btn"
          icon="el-icon-search"
          @click="onSearchButtonClick"
        ></el-button>
        <!-- 添加 -->
        <el-button
          type="primary"
          :disabled="disabled"
          class="search-button"
          @click="addStu"
          v-has="'add'"
        >添加项目</el-button>
      </div>
      <!-- 选择班级 -->
      <div class="select-class">
        <el-form>
          <el-form-item label="选择班级:">
            <el-select
              v-model="classes"
              filterable
              @visible-change="classVisible"
              @change="classChange"
              placeholder="请选择"
            >
              <el-option label="全部" value="all"></el-option>
              <el-option
                v-for="(item, index) in classOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <!-- excel导出 -->
      <div class="export-form">
        <el-button icon="iconfont icon-Excel" @click="exportExcel">导出excel数据</el-button>
      </div>
      <!-- 表格 -->
      <div class="stu-table">
        <el-table :data="stuData" v-loading="loading" border style="width: 100%">
          <el-table-column prop="headimgurl" align="center" label="头像" width="80">
            <template slot-scope="scope">
              <el-avatar shape="square" :size="50" fit="fill" :src="scope.row.headimgurl"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="name" align="center" label="姓名" width="180"></el-table-column>
          <el-table-column prop="class" align="center" label="班级"></el-table-column>
          <el-table-column prop="productUrl" align="center" label="项目"></el-table-column>
          <el-table-column align="center" label="操作">
            <!-- 2.5 v-slot  2.4 slot-scope-->
            <template v-slot="{ row }">
              <el-button
                type="primary"
                class="btn"
                icon="el-icon-view"
                v-has="'read'"
                @click="$router.push({ path: '/StudentManager/Profill' })"
              >查看</el-button>
              <el-button
                type="primary"
                class="btn"
                icon="el-icon-edit"
                @click="editStu(row)"
                v-has="'edit'"
              >编辑</el-button>
              <el-button
                type="danger"
                class="btn"
                icon="el-icon-delete"
                @click="deleteStu(row)"
                v-has="'delete'"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          background
          hide-on-single-page
          layout="prev, pager, next"
          @current-change="changePage"
          :page-size="dataCount"
          :total="total"
        ></el-pagination>
      </div>
      <!-- 弹出框 -->
      <Dialog></Dialog>
    </div>
  </div>
</template>

<script>
import * as api from "@/api"
import qee from "qf-export-excel"
import Dialog from "@/components/Dialog"
import {mapState} from "vuex"
  export default {
    /* 自定义指令，用于鉴权 */
    directives:{
      'has':{
        inserted(el,binding,vnode){
          //console.log(el);
          //console.log(binding);
          let permissionFiled = binding.value//"delete"
          //permissionFiled是允许的权限
          let haspermission = vnode.context.userButtons.includes(permissionFiled)
          if(!haspermission){
            el.disabled = true;
            let oldclassName = el.className
            el.className = oldclassName +" "+"is-disabled"
          }
          //console.log(haspermission);
        }
      }
    },
    components:{
      Dialog
    },
    computed:{
      ...mapState(['userButtons'])
    },
    data() {
      return {
        searchValue:"",
        loading: false,
        searchList: [],
        disabled: false,
        classes:"",
        classOptions: [],
        stuData: [
         /*  {name:'123',headimgurl:'123',class:'123',productUrl:''} */
        ],
        dataCount: 5, // 每页展示的数量
        total: 0, // 总共的数据条数
      };
    }, 
    methods: {
      //点击搜索
      onSearchButtonClick(){},
      //点击搜索框失去焦点
      searchBlur(){},
      // 搜索框选中值发生变化的事件
      searchTextChange(searchText) {
        //console.log(searchText);
      },
       clear() {
        //情况输入框内容的时候,表格应该显示所有的内容
      },
       remoteMethod(query) {
        // 键盘弹起的时候获取输入值
      },
      //添加学生
      addStu(){
        //dialogVisible在dialog，用event bus
        this.$bus.$emit("addstudents");
      },
      // 班级选择框展开/收起触发的事件
      classVisible(isVisible) {
        //展开的时候需要获取数据,调用获取列表的方法
        //console.log(isVisible);//true false
        if(isVisible){
          api.getclassesApi().then(res=>{
            this.classOptions = res.data.data
          })
        }
      },
      //点击选择班级的时候
      classChange(query) {
        //console.log("classchange======", query);//全部all
        //如果query是all代表要显示所有的数据,后台的设定是,class字段传空字符串就返回所有班级的数据,所以一下用一个三元表达式来处理
        //query就是选择的内容
        if(query!=='all'){
          this.updateStuTable("","",query)
        }
      },
       // 编辑学员
      editStu(row) {
        //和添加一样
        this.$bus.$emit("editstudents",row);
      },
        // 删除学员
      deleteStu(row) {
        let {sId} = row;
        //交互
        this.$confirm('此操作将永久删除该学生信息, 是否继续?', '提示', {
          confirmButtonText: '我要删除',
          cancelButtonText: '我不想删除了',
          type: 'warning'
        }).then(() => {

        api.delstuApi(sId).then(res=>{
          console.log(res);
          if(res.data.state){
           this.updateStuTable()
         }else{
           if(res.data.code==='10026'){
             this.$message({
              message: res.data.msg,
              type: 'error'
           });
           }else{
             this.$message({
              message: '删除失败，该学生信息已经被删除！',
              type: 'error'
           });
           }
        }
     }).catch(err=>{
       console.log(err);
       this.$message({
          message: '删除失败，检查网络！',
          type: 'error'
        });
     })

          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });

      },
       // 分页器页码发生改变的时候触发的事件
      changePage(page) {
        // 点击分页切换的时候 需要判断是否搜索了 如果搜索了 那么就应该在搜索结果中 进入第后面页码数据
      },
      //更新表格
      updateStuTable(page="",count="",classes=""){
        this.loading = true;
        api.getstulistApi(page,count,classes).then(res=>{
          //console.log(res.data.data);
          this.loading = false;//成功关闭
          if(res.data.state){
            this.stuData = res.data.data
          }
        }).catch(err=>{
           this.loading = false;//失败关闭
          console.log(err);
        })
      },
       //导出表格excel
      exportExcel() {
        let titleList = [
          {
            title:'头像',
            key:'headimgurl'
          },
           {
            title:'名字',
            key:'name'
          },
           {
            title:'项目地址',
            key:'productUrl'
          },
           {
            title:'班级',
            key:'calss'
          },
           {
            title:'城市',
            key:'city'
          },
           {
            title:'创建时间',
            key:'cTime'
          }
        ]

        qee(titleList,this.stuData,"学生数据一览表")
      },

    },
    mounted() {
     this.updateStuTable()
     this.$bus.$on("updatestudents",()=>{
       this.updateStuTable()
     })
    }
  };
</script>

<style lang="less" scoped>
.search {
  display: flex;
  height: 40px;
  justify-content: left;
  align-items: center;
  margin-top: 25px;
  .search-input {
    width: 300px;
  }
  .search-btn {
    margin-left: 10px;
  }
}
/* 表格 */
& /deep/ .is-leaf {
  height: 60px;
}
.select-class {
  float: left;
  margin-top: 25px;
}
.el-form-item {
  display: flex;
}
.stu-table .btn {
  width: 65px;
  height: 25px;
  padding: 0;
}
.export-form {
  margin-top: 50px;
  position: relative;
}
& /deep/ .icon-Excel {
  color: green;
  font-size: 20px;
  margin-right: 3px;
}
.el-button--default {
  padding: 6px;
  position: absolute;
  right: 0;
}
</style>